<?php
/**
 * 直播间弹幕
 */

namespace App\Models\CacheModel\live;


use think\Cache;
use think\Db;
use think\Log;

class LiveMessage
{
    /**
     * 初始化直播弹幕表
     * @param string $tableName 表名
     * @return bool
     */
    public function initTable(string $tableName): bool
    {
        $cacheKey = 'table_exist:' . $tableName;
        $tableExist = Cache::get($cacheKey, 0);

        if ($tableExist)
        {
            return true;
        }

        $isTable = Db::query('select `TABLE_NAME` from `INFORMATION_SCHEMA`.`TABLES` where `TABLE_SCHEMA`="live_data" and `TABLE_NAME`="' . $tableName . '"');
        if (!$isTable)
        { // 表不存在则创建
            try
            {
                $str = "CREATE TABLE `live_data`.`{$tableName}` (
                          `id` int(11) NOT NULL AUTO_INCREMENT,
                          `uid` int(11) NOT NULL DEFAULT 0 COMMENT '用户ID/后台用户ID',
                          `type` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=>app,2=>后台',
                          `live_id` int(11) NOT NULL DEFAULT 0 COMMENT '直播间ID',
                          `content` varchar(255) NOT NULL DEFAULT '' COMMENT '弹幕',
                          `create_time` bigint(15) NOT NULL DEFAULT 0 COMMENT '发送时间',
                          PRIMARY KEY (`id`),
                          KEY `uid` (`uid`)
                        )  ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='直播弹幕信息'";
                // 创建数据库
                Db::execute($str);
            }
            catch (\Exception $e)
            {
                if (!strstr($e->getMessage(), 'already exists'))
                {
                    Log::write("直播间弹幕表创建失败：{$e->getMessage()};File:{$e->getFile()};Line:{$e->getLine()}", 'error', true);
                    return false;
                }
            }
        }

        Cache::set($cacheKey, 1, 86400);
        return true;
    }

    /**
     * 写入弹幕数据
     * @param int $liveRecordId
     * @param array $insertData
     * @param int $inSign
     * @return int|string   返回弹幕数据ID 或 0
     */
    public function insertMessage(int $liveRecordId, array $insertData, int $inSign)
    {

        $tableName = 'live_message_' . $liveRecordId;

        $initTable = $this->initTable($tableName);

        if ($initTable)
        {
            try
            {
                $messageId = Db::table('`live_data`.' . $tableName)->insertGetId($insertData);
                // 弹幕数新增
                (new LiveStatusDataRecord())->setMinuteInc($insertData['live_id'], 'comment_num', 1);
                // 用户热度数 自增
                (new LiveRecordUserHot())->userHotInc($insertData['uid'], $insertData['live_id'], $liveRecordId, 'message_hot', 1);
                if ($inSign)
                {
                    // 每日星座点赞 热度自增
                    (new LiveSignHotDay())->setDaySignInc($insertData['live_id'], $liveRecordId, $inSign, 1);
                }
                return $messageId;
            }
            catch (\Exception $e)
            {
                Log::write("弹幕写入异常：{$e->getMessage()};File:{$e->getFile()};Line:{$e->getLine()}", 'error', true);
                return 0;
            }
        } else
        {
            return 0;
        }
    }
}
